package com.fh.alipay.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayDataBillAccountlogQueryRequest;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fh.alipay.AliPayApi;
import com.fh.alipay.AliPayApiConfig;
import com.fh.alipay.AliPayApiConfigKit;
import com.fh.alipay.dto.*;
import com.fh.alipay.entity.AliPayBean;
import com.fh.alipay.kit.IpKit;
import com.fh.alipay.model.query.GoodsQuery;
import com.fh.alipay.model.query.OrderQuery;
import com.fh.alipay.po.*;
import com.fh.alipay.po.Goods;
import com.fh.alipay.service.IGoodsService;
import com.fh.alipay.service.ILqiMerchantService;
import com.fh.alipay.service.IMerchantService;
import com.fh.alipay.service.IOrderService;
import com.fh.alipay.utils.InputParamSignUtil;
import com.fh.alipay.utils.MD5Utils;
import com.fh.alipay.utils.SnowflakeIdWorker;
import com.fh.alipay.utils.StringUtils;
import com.fh.alipay.vo.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.relational.core.sql.In;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>支付宝支付</p>
 *
 * @author fh
 */
@RestController
@RequestMapping("/aliPay")
public class AliPayController extends AbstractAliPayApiController {
    private static final Logger log = LoggerFactory.getLogger(AliPayController.class);

    @Resource
    private AliPayBean aliPayBean;

    @Resource
    private HttpSession session;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private IMerchantService merchantService;

    @Resource
    private ILqiMerchantService lqiMerchantService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private IOrderService orderService;

    @Resource
    private HttpServletRequest request;

    @Value("${lqi.url}")
    private String url;

    @Value("${lqi.app_key}")
    private String app_key;

    @Value("${lqi.secret}")
    private String secret;

    @Value("${ali.quit_url}")
    private String quitUrl;
    @Value("${ali.return_url}")
    private String returnUrl;

    // 普通公钥模式
    private final static String NOTIFY_URL = "/aliPay/notify_url";

    private final static String RETURN_URL = "/aliPay/return_url";

    private final static String CALLBACK_URL = "/aliPay/callback_url";

    @Override
    public AliPayApiConfig getApiConfig() throws AlipayApiException {
        List<Merchant> list = merchantService.list();
        Merchant merchant;
        if (CollUtil.isNotEmpty(list)) {
            merchant = list.get(0);
        } else {
            Merchant other = new Merchant();
            other.setAppId(aliPayBean.getAppId());
            other.setPrivateKey(aliPayBean.getPrivateKey());
            other.setPublicKey(aliPayBean.getPublicKey());
            other.setServerUrl(aliPayBean.getServerUrl());
            merchant = other;
        }
        AliPayApiConfig aliPayApiConfig;
        try {
            aliPayApiConfig = AliPayApiConfigKit.getApiConfig(merchant.getAppId());
        } catch (Exception e) {
            aliPayApiConfig = AliPayApiConfig.builder()
                    .setAppId(merchant.getAppId())
                    .setAliPayPublicKey(merchant.getPublicKey())
                    .setAppCertPath(aliPayBean.getAppCertPath())
                    .setAliPayCertPath(aliPayBean.getAliPayCertPath())
                    .setAliPayRootCertPath(aliPayBean.getAliPayRootCertPath())
                    .setCharset("UTF-8")
                    .setPrivateKey(merchant.getPrivateKey())
                    .setServiceUrl(aliPayBean.getServerUrl())
                    .setSignType("RSA2")
                    // 普通公钥方式
                    .build();
        }
        return aliPayApiConfig;
    }

    @RequestMapping("")
    public String index() {
        return "欢迎使用支付宝支付";
    }

    @RequestMapping("/test")
    public AliPayApiConfig test() {
        AliPayApiConfig aliPayApiConfig = AliPayApiConfigKit.getAliPayApiConfig();
        String charset = aliPayApiConfig.getCharset();
        log.info("charset>" + charset);
        return aliPayApiConfig;
    }

    /**
     * 根据手机号校验用户次数
     *
     * @param contactTel
     * @return
     */
    @GetMapping("/verifyOrder")
    public ApiResult<String> verifyOrder(String contactTel) {
        List<Order> orders = orderService.queryByContactTel(contactTel);
        if (CollUtil.isNotEmpty(orders) && orders.size() >= 2) {
            return ApiResult.error("当日次数已用完");
        }
        return ApiResult.ok();
    }

    /**
     * 支付宝发起支付
     *
     * @param response
     */
    @RequestMapping(value = "/wapPay")
    public void wapPay(HttpServletResponse response, @RequestParam("product_id") Integer product_id) {

        GoodsQuery query = new GoodsQuery();
        query.setGoodsId(Convert.toStr(product_id));
        Goods oneByQuery = goodsService.getOneByQuery(query);
        String totalAmount = oneByQuery.getGoodsCurrentPrice();

        String body = "充值";
        String subject = "充值";
        String passBackParams = "1";
        String notifyUrl = aliPayBean.getDomain() + NOTIFY_URL;

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setPassbackParams(passBackParams);
        model.setQuitUrl(quitUrl);
        String outTradeNo = SnowflakeIdWorker.getUUID();
        System.out.println("wap outTradeNo>" + outTradeNo);
        model.setOutTradeNo(outTradeNo);
        model.setProductCode("QUICK_WAP_PAY");

        try {
            AliPayApi.wapPay(response, model, returnUrl, notifyUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付完成调用下单
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/return_url")
    public String returnUrl(HttpServletRequest request) {
        System.out.println("return_url---------------");
        List<Merchant> list = merchantService.list();
        Merchant merchant;
        if (CollUtil.isNotEmpty(list)) {
            merchant = list.get(0);
        } else {
            Merchant other = new Merchant();
            other.setAppId(aliPayBean.getAppId());
            other.setPrivateKey(aliPayBean.getPrivateKey());
            other.setPublicKey(aliPayBean.getPublicKey());
            other.setServerUrl(aliPayBean.getServerUrl());
            merchant = other;
        }
        try {
            // 获取支付宝GET过来反馈信息
            Map<String, String> map = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                log.info("request:{}", entry.getKey() + " = " + entry.getValue());
            }
            String out_trade_no = map.get("out_trade_no");

            boolean verifyResult = AlipaySignature.rsaCheckV1(map, merchant.getPublicKey(), "UTF-8",
                    "RSA2");

            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码
                log.info("return_url 验证成功");
                System.out.println("=======================");
//                OrderDto orderDto = (OrderDto) session.getAttribute(out_trade_no);
//                log.info("----orderDto:{}", orderDto);
//                LqiDto lqiDto = new LqiDto();
//                lqiDto.setApp_key(orderDto.getAppKey());
//                lqiDto.setTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:dd")));
//                lqiDto.setMethod("order.direct.add");
//                BizContent bizContent = new BizContent();
//                BeanUtil.copyProperties(orderDto, bizContent);
//                bizContent.setCallback_url(aliPayBean.getDomain() + CALLBACK_URL);
//                bizContent.setCharge_ip(IpKit.getRealIp(request));
//                bizContent.setCustomer_order_no(out_trade_no);
//                lqiDto.setBiz_content(bizContent);
//                lqiDto.setSign(InputParamSignUtil.sign(secret, lqiDto));
//                Map<String, String> requestMap = setRequestMap(lqiDto);
//                HttpHeaders headers = new HttpHeaders();
//                headers.setContentType(MediaType.APPLICATION_JSON);
//                HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestMap), headers);
//                log.info("下单接口入参：" + JSONObject.toJSONString(requestEntity));
//                ResponseEntity<String> responseEntity =
//                        restTemplate.postForEntity(url, requestEntity, String.class);
//                String responseEntityBody = responseEntity.getBody();
//                log.info("下单接口回参：" + JSONObject.toJSONString(responseEntityBody));
                return "success";
            } else {
                System.out.println("return_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @RequestMapping(value = "/orderDirectAdd", method = {RequestMethod.GET, RequestMethod.POST})
    public BaseResponse orderDirectAdd(@Valid OrderDto orderDto, BindingResult bindingResult) {
        System.out.println("========================" + orderDto);
        if (bindingResult.hasErrors()) {
            return new BaseResponse(-1, "参数有误", null, null);
        }
        Order po = new Order();
        LocalDateTime now = LocalDateTime.now();
        po.setCreateTime(now);
        po.setUpdateTime(now);
        po.setOrderStatus("processing");
        po.setChargeIp(IpKit.getRealIp(request));
        po.setChargeAccount(orderDto.getCharge_account());
        po.setBuyNum(orderDto.getBuy_num());
        po.setAccountType(orderDto.getAccount_type());
        po.setCustomerOrderNo(orderDto.getCustomer_order_no());
        po.setProductId(orderDto.getProduct_id());
        po.setChargeAccount(orderDto.getCharge_account());
        po.setChargeGameName(orderDto.getCharge_game_name());
        po.setChargeGameRegion(orderDto.getCharge_game_region());
        po.setChargeGameRole(orderDto.getCharge_game_role());
        po.setChargeGameSrv(orderDto.getCharge_game_srv());
        po.setChargePassword(orderDto.getCharge_password());
        po.setChargeType(orderDto.getCharge_type());
        po.setContactQq(orderDto.getContact_qq());
        po.setContactTel(orderDto.getContact_tel());
        po.setProductName(orderDto.getProductName());
        po.setShopType(orderDto.getShop_type());
        orderService.save(po);

        LqiMerchant lqiMerchant = lqiMerchantService.getById(1);
        String appKey = lqiMerchant.getAppKey();
        LqiDto lqiDto = new LqiDto();
        lqiDto.setApp_key(appKey);
        lqiDto.setTimestamp(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:dd")));
        lqiDto.setMethod("order.direct.add");
        BizContent bizContent = new BizContent();
        BeanUtil.copyProperties(orderDto, bizContent);
        bizContent.setCallback_url(aliPayBean.getDomain() + CALLBACK_URL);
        bizContent.setCharge_ip(IpKit.getRealIp(request));
        lqiDto.setBiz_content(bizContent);
        lqiDto.setSign(InputParamSignUtil.sign(secret, lqiDto));
        Map<String, String> requestMap = setRequestMap(lqiDto);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestMap), headers);
        log.info("下单接口入参：" + JSONObject.toJSONString(requestEntity));
        ResponseEntity<BaseResponse> responseEntity =
                restTemplate.postForEntity(url, requestEntity, BaseResponse.class);
        BaseResponse baseResponse = responseEntity.getBody();
        log.info("下单接口回参：" + baseResponse);
        return baseResponse;
    }

    @RequestMapping(value = "/notify_url")
    public String notifyUrl(HttpServletRequest request) {
        System.out.println("notify_url");
        List<Merchant> list = merchantService.list();
        Merchant merchant;
        if (CollUtil.isNotEmpty(list)) {
            merchant = list.get(0);
        } else {
            Merchant other = new Merchant();
            other.setAppId(aliPayBean.getAppId());
            other.setPrivateKey(aliPayBean.getPrivateKey());
            other.setPublicKey(aliPayBean.getPublicKey());
            other.setServerUrl(aliPayBean.getServerUrl());
            merchant = other;
        }
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);

            for (Map.Entry<String, String> entry : params.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }

            boolean verifyResult = AlipaySignature.rsaCheckV1(params, merchant.getPublicKey(), "UTF-8", "RSA2");

            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
                System.out.println("notify_url 验证成功success");
                return "success";
            } else {
                System.out.println("notify_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    /**
     * 订单查询
     *
     * @param customer_order_no
     * @return
     */
    @PostMapping("/orderInfoGet")
    public BaseResponse orderInfoGet(String customer_order_no) {
        LqiDto lqiDto = new LqiDto();
        List<LqiMerchant> lqiMerchants = lqiMerchantService.list();
        String appKey;
        if (CollUtil.isNotEmpty(lqiMerchants)) {
            appKey = lqiMerchants.get(0).getAppKey();
        } else {
            appKey = app_key;
        }
        lqiDto.setApp_key(appKey);
        lqiDto.setMethod("order.info.get");
        lqiDto.setTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:dd")));
        BizContent bizContent = new BizContent();
        bizContent.setCustomer_order_no(customer_order_no);
        lqiDto.setBiz_content(bizContent);
        lqiDto.setSign(InputParamSignUtil.sign(secret, lqiDto));
        Map<String, String> requestMap = setRequestMap(lqiDto);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestMap), headers);
        log.info("订单查询接口入参：" + JSONObject.toJSONString(requestEntity));
        ResponseEntity<BaseResponse> responseEntity =
                restTemplate.postForEntity(url, requestEntity, BaseResponse.class);
        BaseResponse baseResponse = responseEntity.getBody();
        log.info("订单查询接口回参：" + baseResponse);
        return baseResponse;
    }

    /**
     * 授权产品列表查询
     *
     * @return
     */
    @PostMapping("/goodsListGet")
    public BaseResponse goodsListGet() {
        LqiDto lqiDto = new LqiDto();
        List<LqiMerchant> lqiMerchants = lqiMerchantService.list();
        String appKey;
        if (CollUtil.isNotEmpty(lqiMerchants)) {
            appKey = lqiMerchants.get(0).getAppKey();
        } else {
            appKey = app_key;
        }
        lqiDto.setApp_key(appKey);
        lqiDto.setMethod("goods.list.get");
        lqiDto.setTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:dd")));
        lqiDto.setSign(InputParamSignUtil.sign(secret, lqiDto));
        Map<String, String> requestMap = setRequestMap(lqiDto);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestMap), headers);
        log.info("授权产品列表查询接口入参：" + JSONObject.toJSONString(requestEntity));
        ResponseEntity<BaseResponse> responseEntity =
                restTemplate.postForEntity(url, requestEntity, BaseResponse.class);
        BaseResponse baseResponse = responseEntity.getBody();
        log.info("授权产品列表查询接口回参：" + baseResponse);
        return baseResponse;
    }

    private static Map<String, String> setRequestMap(LqiDto lqiDto) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("app_key", lqiDto.getApp_key());
        map.put("method", lqiDto.getMethod());
        map.put("timestamp", lqiDto.getTimestamp());
        map.put("version", "2.0");
        map.put("format", "json");
        map.put("charset", "utf-8");
        map.put("sign_type", "md5");
        map.put("app_auth_token", "");
        map.put("biz_content", JSONObject.toJSONString(lqiDto.getBiz_content()));
        map.put("sign", lqiDto.getSign());
        return map;
    }

    /**
     * 猎奇回调
     *
     * @param info
     * @return
     */
    @PostMapping("/callback_url")
    public String callback_url(@RequestBody String info) {
        System.out.println("callback_url:" + info);
        try {
            // 获取猎奇POST过来反馈信息
            if (StrUtil.isBlank(info)) {
                return "failure";
            }
            JSONObject jsonObject = JSONObject.parseObject(info);
            String customer_order_no = jsonObject.getString("customer_order_no");
            String order_status = jsonObject.getString("order_status");
            String charge_finish_time = jsonObject.getString("charge_finish_time");
            String order_id = jsonObject.getString("order_id");
            Map<String, String> map = new HashMap<>();
            map.put("order_id", order_id);
            map.put("charge_finish_time", charge_finish_time);
            map.put("customer_order_no", customer_order_no);
            map.put("order_status", order_status);
            map.put("recharge_description", jsonObject.getString("recharge_description"));
            map.put("product_id", jsonObject.getString("product_id"));
            map.put("price", jsonObject.getString("price"));
            map.put("buy_num", jsonObject.getString("buy_num"));
            map.put("operator_serial_number", jsonObject.getString("operator_serial_number"));
            net.sf.json.JSONObject resultJson = net.sf.json.JSONObject.fromObject(map);
            System.out.println(resultJson);
            char[] s = JSONObject.toJSONString(resultJson, SerializerFeature.WriteMapNullValue).toCharArray();
            Arrays.sort(s);
            String outputSignOriginalStr = new String(s) + secret;
            String sign = MD5Utils.MD5(outputSignOriginalStr);

            if (sign.equals(jsonObject.getString("sign"))) {
                // TODO 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
                System.out.println("callback_url 验证成功success");
                OrderQuery query = new OrderQuery();
                query.setCustomerOrderNo(customer_order_no);
                Order oneByQuery = orderService.getOneByQuery(query);
                Order updateOrder = new Order();
                updateOrder.setId(oneByQuery.getId());
                updateOrder.setOrderStatus(order_status);
                updateOrder.setUpdateTime(LocalDateTime.now());
                updateOrder.setChargeFinishTime(LocalDateTime.parse(charge_finish_time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                updateOrder.setOrderId(order_id);
                orderService.updateById(updateOrder);
                return "success";
            } else {
                System.out.println("callback_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (Exception e) {
            log.error("callback_url error:" + e.getMessage());
            return "failure";
        }
    }

    /**
     * 支付宝商家账户账务明细查询
     */
    @PostMapping(value = "/accountLogQuery")
    public String accountLogQuery(AccountLogQueryDto accountLogQueryDto) {
        System.out.println("accountLogQuery-----" + accountLogQueryDto);
        try {
            AlipayDataBillAccountlogQueryModel model = new AlipayDataBillAccountlogQueryModel();
            model.setAgreementNo(accountLogQueryDto.getAgreement_no());
            model.setAgreementProductCode(accountLogQueryDto.getAgreement_product_code());
            model.setAlipayOrderNo(accountLogQueryDto.getAlipay_order_no());
            model.setBillUserId(accountLogQueryDto.getBill_user_id());
            model.setStartTime(accountLogQueryDto.getStart_time());
            model.setEndTime(accountLogQueryDto.getEnd_time());
            model.setTransCode(accountLogQueryDto.getTrans_code());
            model.setPageNo(accountLogQueryDto.getPage_no());
            model.setPageSize(accountLogQueryDto.getPage_size());
            model.setMerchantOrderNo(accountLogQueryDto.getMerchant_order_no());
            return AliPayApi.accountLogQueryToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询交易投诉列表
     */
    @PostMapping(value = "/merchantTradeComplainBatchQuery")
    public String merchantTradeComplainBatchQuery(MerchantTradeComplainBatchQueryDto merchantTradeComplainBatchQueryDto) {
        System.out.println("merchantTradeComplainBatchQuery-----" + merchantTradeComplainBatchQueryDto);
        try {
            AlipayMerchantTradecomplainBatchqueryModel model = new AlipayMerchantTradecomplainBatchqueryModel();
            model.setTargetInfos(merchantTradeComplainBatchQueryDto.getTarget_infos());
            model.setStatus(merchantTradeComplainBatchQueryDto.getStatus());
            model.setBeginTime(merchantTradeComplainBatchQueryDto.getBegin_time());
            model.setEndTime(merchantTradeComplainBatchQueryDto.getEnd_time());
            model.setPageNum(merchantTradeComplainBatchQueryDto.getPage_num());
            model.setPageSize(merchantTradeComplainBatchQueryDto.getPage_size());
            return AliPayApi.merchantTradeComplainBatchQueryToResponse(model).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }


    @RequestMapping(value = "/wapPayTest")
    public void wapPayTest(HttpServletResponse response) {

//        List<Merchant> list = merchantService.list(Wrappers.lambdaQuery(Merchant.class).eq(Merchant::getDelFlag, 1));
        List<LqiMerchant> lqiMerchants = lqiMerchantService.list();
        String appKey;
//        String domain;
//        if (CollUtil.isNotEmpty(list)) {
//            domain = list.get(0).getDomain();
//        } else {
//            domain = aliPayBean.getDomain();
//        }
        if (CollUtil.isNotEmpty(lqiMerchants)) {
            appKey = lqiMerchants.get(0).getAppKey();
        } else {
            appKey = app_key;
        }

        OrderDto orderDto = new OrderDto();
        orderDto.setTotalAmount("0.01");
        orderDto.setQuit_url("https://www.baidu.com");
        orderDto.setSubject("充值");


        orderDto.setDomain(aliPayBean.getDomain());
        orderDto.setAppKey(appKey);
        System.out.println("orderDto================" + orderDto);

        String body = orderDto.getSubject();
        String subject = orderDto.getSubject();
        String totalAmount = orderDto.getTotalAmount();
        String quit_url = orderDto.getQuit_url();
        String passBackParams = "1";
        String returnUrl = aliPayBean.getDomain() + "/aliPay/return_url_test";
        String notifyUrl = aliPayBean.getDomain() + NOTIFY_URL;

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setPassbackParams(passBackParams);
        model.setQuitUrl(quit_url);
        String outTradeNo = SnowflakeIdWorker.getUUID();
        session.setAttribute(outTradeNo, orderDto);
        System.out.println("wap outTradeNo>" + outTradeNo);
        model.setOutTradeNo(outTradeNo);
        model.setProductCode("QUICK_WAP_PAY");

        try {
            AliPayApi.wapPay(response, model, returnUrl, notifyUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/return_url_test")
    public String returnUrlTest(HttpServletRequest request) {
        System.out.println("return_url---------------");
        List<Merchant> list = merchantService.list();
        Merchant merchant;
        if (CollUtil.isNotEmpty(list)) {
            merchant = list.get(0);
        } else {
            Merchant other = new Merchant();
            other.setAppId(aliPayBean.getAppId());
            other.setPrivateKey(aliPayBean.getPrivateKey());
            other.setPublicKey(aliPayBean.getPublicKey());
            other.setServerUrl(aliPayBean.getServerUrl());
            merchant = other;
        }
        try {
            // 获取支付宝GET过来反馈信息
            Map<String, String> map = AliPayApi.toMap(request);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                log.info("request:{}", entry.getKey() + " = " + entry.getValue());
            }
            String out_trade_no = map.get("out_trade_no");

            boolean verifyResult = AlipaySignature.rsaCheckV1(map, merchant.getPublicKey(), "UTF-8",
                    "RSA2");

            if (verifyResult) {
                // TODO 请在这里加上商户的业务逻辑程序代码
                log.info("return_url 验证成功");
                System.out.println("=======================");
                OrderDto orderDto = (OrderDto) session.getAttribute(out_trade_no);
                log.info("----orderDto:{}", orderDto);


                LqiDto lqiDto = new LqiDto();
                lqiDto.setApp_key("683948911");
                lqiDto.setTimestamp(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:dd")));
                lqiDto.setMethod("order.direct.add");
                BizContent bizContent = new BizContent();
                bizContent.setAccount_type("mobile");
                bizContent.setBuy_num(1);
                bizContent.setProduct_id(10000586);
                bizContent.setCallback_url(orderDto.getDomain() + CALLBACK_URL);
                bizContent.setCharge_ip(IpKit.getRealIp(request));
                bizContent.setCustomer_order_no(StringUtils.getOutTradeNo());
                bizContent.setCharge_account("15717141167");
                lqiDto.setBiz_content(bizContent);
                lqiDto.setSign(InputParamSignUtil.sign(secret, lqiDto));


                Map<String, String> requestMap = setRequestMap(lqiDto);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(requestMap), headers);
                log.info("下单接口入参：" + JSONObject.toJSONString(requestEntity));
                ResponseEntity<String> responseEntity =
                        restTemplate.postForEntity(url, requestEntity, String.class);
                String responseEntityBody = responseEntity.getBody();
                log.info("下单接口回参：" + JSONObject.toJSONString(responseEntityBody));
                return "success";
            } else {
                System.out.println("return_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
    }
}